    //
//  PlayerController.m
//  Quiz
//
//  Created by AnhLH-Oriolus on 28/07/2011.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "PlayerController.h"
#import "countryquizAppDelegate.h"
#import "MainController.h"

@implementation PlayerController

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
-(id)init{
	self = [super init];
	
	isEditing = NO;
	_indexMenuSelect = -1;
	[self loadData];
	return self;
}

-(BOOL)openDb{
	NSString *path = [NSString stringWithFormat:@"%@/FootballTeam.db",g_strMainBundlePath];
	db = [FMDatabase databaseWithPath:path];
    if (![db open]) {
        NSLog(@"Could not open db.");
		return FALSE;
    }
	NSLog(@"DB opened successfully");
	return TRUE;
}


-(void)loadData{
	currPlayer = @"";
	if(arrPlayer){
		[arrPlayer removeAllObjects];
	}else {
		arrPlayer = [[NSMutableArray alloc] init];
	}
	
	if([self openDb]){
		FMResultSet *rs = [db executeQuery:@"select PlayerName from Player"];	
		while([rs next])
		{
			NSString *name = [rs stringForColumn:@"PlayerName"];
			[arrPlayer addObject:name];
		}
		[rs close];
		[self closeDb];
	}else {
		NSLog(@"Cannot open database");
	}
}

-(void)closeDb{
    if (db && [db open]) {
		[db close];
    }
}

// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
	UIImageView *v = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
	[v setImage:[UIImage imageNamed:@"images/addPlayerBkgr.png"]];
	[v setUserInteractionEnabled:YES];
	self.view = v;
	[v release];
	
//header bar
	UIImage *img;
	
	UIImageView *vBar = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
	[vBar setImage:[UIImage imageNamed:@"images/bar.png"]];
	[vBar setUserInteractionEnabled:YES];
	[self.view addSubview:vBar];
	
	FontLabel *lblScore = [[FontLabel alloc] initWithFrame:CGRectMake(0, 0, 320, 50) fontName:@"scoreboard" pointSize:30];
	[lblScore setBackgroundColor:[UIColor clearColor]];
	lblScore.textAlignment = UITextAlignmentCenter;
	lblScore.textColor = [UIColor colorWithRed:243 green:255 blue:62 alpha:1.0];
	lblScore.text = @"Select player";
	[vBar addSubview:lblScore];
	[lblScore release];
	
	//add btn
	img = [UIImage imageNamed:@"images/add_btn.png"];
	UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(320-img.size.width-5, 5, img.size.width, img.size.height)];
	[btn setBackgroundColor:[UIColor clearColor]];
	[btn setImage:img forState:UIControlStateNormal];
	[btn addTarget:nil action:@selector(addPlayer) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:btn];
	[btn release];
	
	//edit btn
	img = [UIImage imageNamed:@"images/edit_btn.png"];
	UIButton *btn1 = [[UIButton alloc] initWithFrame:CGRectMake(5, 5, img.size.width, img.size.height)];
	[btn1 setBackgroundColor:[UIColor clearColor]];
	[btn1 setImage:img forState:UIControlStateNormal];
	[btn1 addTarget:nil action:@selector(editPlayer) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:btn1];
	[btn1 release];

//tableView
	_tableView = [[UITableView alloc] initWithFrame:CGRectMake(160-95, 60, 190, 246) style:UITableViewStylePlain];	
	[_tableView setBackgroundColor:[UIColor clearColor]];
	_tableView.dataSource = self;
	_tableView.delegate = self;
	[self.view addSubview:_tableView];
	[_tableView release];
	
//back
	img = [UIImage imageNamed:@"images/home_btn.png"];
	UIButton *btnBack = [[UIButton alloc] initWithFrame:CGRectMake(5, 480-img.size.height-5, img.size.width, img.size.height)];
	[btnBack setBackgroundColor:[UIColor clearColor]];
	[btnBack setImage:img forState:UIControlStateNormal];
	[btnBack addTarget:nil action:@selector(backToMenu) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:btnBack];
	[btnBack release];
//PlayGame
	img = [UIImage imageNamed:@"images/play_button.png"];
	UIButton *btnPlay = [[UIButton alloc] initWithFrame:CGRectMake(320-img.size.width-5, 480-img.size.height-5, img.size.width, img.size.height)];
	[btnPlay setBackgroundColor:[UIColor clearColor]];
	[btnPlay setImage:img forState:UIControlStateNormal];
	btnPlay.showsTouchWhenHighlighted = YES;
	[btnPlay addTarget:nil action:@selector(playQuiz) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:btnPlay];
	[btnPlay release];
}

-(void)addPlayer{
	[g_AppDelegate.mainCtrl addPlayerView];
}

-(void)addNewPlayerWithName:(NSString *)playerName{
	if(!playerName || [playerName isEqualToString:@""])
		return;
	
	if([self openDb]){
		NSString *sql = [NSString stringWithFormat:@"select PlayerName from Player where PlayerName like '%@'",playerName];
		FMResultSet *rs = [db executeQuery:sql];
		BOOL isExit = FALSE;
		while( [rs next])
		{
			isExit = TRUE;
			break;
		}
		[rs close];
		
		if(!isExit){
			int index = [arrPlayer count];
			sql = [NSString stringWithFormat:@"select max(PlayerID) as maxID from Player"];
			rs = [db executeQuery:sql];
			while( [rs next])
			{
				index = [rs intForColumn:@"maxID"];
				break;
			}
			[rs close];
			
			sql = [NSString stringWithFormat:@"insert into Player values(%d,'%@')", index+1, playerName];
			[db beginTransaction];
			[db executeUpdate:sql];
			[db commit];
			
			[arrPlayer addObject:[playerName retain]];
			[_tableView reloadData];
		}else {
			UIAlertView *al = [[UIAlertView alloc] initWithTitle:@"Your name is exited!" message:@"" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
			[al show];
			[al release];
		}
	
		sql = [NSString stringWithFormat:@"select PlayerName from Player"];
		rs = [db executeQuery:sql];
		while( [rs next])
		{
			NSLog(@"%@", [rs stringForColumn:@"PlayerName"]);
		}
		[rs close];
		
		[self closeDb];
	}
}

-(void)editPlayer{
	isEditing = !isEditing;
	if(isEditing == YES){
		[_tableView setEditing:YES animated: YES];
	}else {
		[_tableView setEditing:NO animated: YES];
	}
	[self performSelector:@selector(refreshTable) withObject:self afterDelay:0.2];
}

-(void)refreshTable{
	[_tableView reloadData];
}


-(void)backToMenu{
	[self.view removeFromSuperview];
	[g_AppDelegate.mainCtrl openMenuViewCtrl];
}


-(void)playQuiz{
	if([currPlayer isEqualToString:@""]){
		UIAlertView *al = [[UIAlertView alloc] initWithTitle:@"Can't start quiz" message:@"PLease select your name" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[al show];
		[al release];
	}else{
		[g_AppDelegate.mainCtrl openPlayGameController:currPlayer];
	}
}

#pragma mark  delegate tableView
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
	UITableViewCell* cell = nil;
	cell = [tableView dequeueReusableCellWithIdentifier:@"0"];
	if(!cell){
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"0"] autorelease];
		cell.textLabel.font = [UIFont fontWithName:@"Arial" size:16];
	}
	
	cell.textLabel.text = [arrPlayer objectAtIndex:indexPath.row];
	
	if (indexPath.row == _indexMenuSelect) {
		UIImage* pImgFosuc=[UIImage imageNamed:@"images/tick.png"];
		UIImageView* pImgView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, pImgFosuc.size.width,pImgFosuc.size.height)];
		pImgView.image=pImgFosuc;
		cell.accessoryView=pImgView;
		[pImgView release];
	}
	else {
		cell.accessoryView=nil;
	}
	
	return cell;
}

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
	return [arrPlayer count];
}

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
	
	_indexMenuSelect = indexPath.row;
	currPlayer = [arrPlayer objectAtIndex:indexPath.row];
	sName = [arrPlayer objectAtIndex:indexPath.row];

	[_tableView reloadData];
}

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
		// Delete the row from the data source
		if (arrPlayer != nil) {
			if([self openDb]){
				NSString *playerName = [arrPlayer objectAtIndex:indexPath.row];
				NSString *sql = [NSString stringWithFormat:@"delete from Player where PlayerName like '%@'",playerName];
				[db beginTransaction];
				[db executeUpdate:sql];
				[db commit];
				
				[self closeDb];
			}
			
			[arrPlayer removeObjectAtIndex:indexPath.row];
		}
		
		NSArray *deleteIndexPaths = [NSArray arrayWithObjects:[NSIndexPath indexPathForRow:indexPath.row inSection:0], nil];
		
		[tableView beginUpdates];
		[tableView deleteRowsAtIndexPaths:deleteIndexPaths withRowAnimation:UITableViewRowAnimationRight];
		[tableView endUpdates];
		
		[tableView reloadData];
		
	}
	
}

/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
*/


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    return YES;
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}


- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end
